package spring.framework.core.io;

import cn.hutool.core.lang.Assert;
import spring.framework.util.ClassUtils;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author pengzh
 * @class ClassPathResource
 * @since 2021-09-23
 */
public class ClassPathResource implements Resource {

    private final String path;

    private ClassLoader classLoader;


    public ClassPathResource(String path) {
        this(path, null);
    }

    public ClassPathResource(String path, ClassLoader classLoader) {
        Assert.notBlank(path, "path can not be blank");
        this.path = path;
        this.classLoader = null != classLoader ? classLoader : ClassUtils.getDefaultClassLoader();
    }


    @Override
    public InputStream getInputStream() throws IOException {
        InputStream inputStream = classLoader.getResourceAsStream(path);
        if (null == inputStream) {
            throw new FileNotFoundException(this.path + " cannot be open it does not found");
        }
        return inputStream;
    }
}
